﻿using System;
using System.Collections.Generic;
using System.Text;
using VideoCache.Spider.FileFetchers;

namespace VideoCache.Spider
{
    public class FetcherFactory
    {
        public static FetcherResult GetFiles(string url, Resolution resolution)
        {
            Uri uri;
            FetcherResult result = null;
            if (Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                IFetcher fetcher = null;

                if (uri.Host.EndsWith("letv.com")) fetcher = new LetvFetcher();
                else if (uri.Host.EndsWith("qq.com")) fetcher = new FlvCDFetcher();
                else if (uri.Host.EndsWith("sohu.com")) fetcher = new SohuFetcher();
                else if (uri.Host.EndsWith("tudou.com")) fetcher = new FlvCDFetcher();
                else if (uri.Host.EndsWith("youku.com")) fetcher = new FlvCDFetcher();

                if (fetcher != null)
                {
                    FetcherResult[] list = fetcher.GetFiles(url);

                    if (list != null && list.Length != 0)
                    {
                        result = Resolve(list, resolution);
                        if (result != null) result.Referer = url;
                    }
                }
            }
            return result;
        }

        static FetcherResult Resolve(FetcherResult[] list, Resolution resolution)
        {
            FetcherResult lastResult = null;

            if (resolution != Resolution.Unknow)
            {
                foreach (FetcherResult result in list)
                {
                    if (result.Resolution == resolution)
                    {
                        lastResult = result;
                        break;
                    }
                }
            }
            else
            {
                foreach (FetcherResult result in list)
                {
                    if (lastResult == null) lastResult = result;
                    else
                    {
                        if ((int)result.Resolution > (int)lastResult.Resolution)
                        {
                            lastResult = result;
                        }
                    }
                }
            }

            return lastResult;
        }
    }
}
